<template>
  <div class="add-contract" v-loading="loading">
    <CommonHeader
      :headerObj="{ title: $t('合同详情') }"
      @left-click="handleBack"
    ></CommonHeader>
    <div class="add-contract-part">
      <van-tabs v-model="activeName">
        <van-tab :title="$t('合同信息')" name="first"></van-tab>
        <van-tab :title="$t('历史版本')" name="second"></van-tab>
      </van-tabs>
      <div v-if="activeName === 'first'">
        <div class="add-contract-base">
          <div class="add-contract-part-con-title">
            {{ $t('抬头信息') }}
          </div>
          <el-form
            :model="templateDetail"
            ref="templateForm"
            label-width="100px"
            :rules="rules"
          >
            <el-row>
              <div class="base-box">
                <el-col :span="24" v-if="!routeQuery.formQuery">
                  <el-form-item
                    :label="$t('变更单号：')"
                    v-if="routeQuery.contractSource == 1"
                  >
                    <div style="display: flex">
                      <el-input
                        disabled
                        v-model="templateDetail.changeNumber"
                        style="margin-right: 8px; width: 60%"
                      ></el-input>
                      <template>
                        <span
                          v-if="routeQuery.contractChangeExamineState == '2'"
                          :class="{
                            failed:
                              routeQuery.contractChangeExamineState == '2',
                          }"
                          class="contractChangeExamineState"
                          style="height: 26px; line-height: 26px"
                          >{{ $t('已驳回') }}</span
                        >
                        <span
                          v-else-if="
                            routeQuery.contractChangeExamineState == '1'
                          "
                          :class="{
                            success:
                              routeQuery.contractChangeExamineState == '1',
                          }"
                          class="contractChangeExamineState"
                          style="height: 26px; line-height: 26px"
                          >{{ $t('已通过') }}</span
                        >
                        <span
                          v-else
                          class="contractChangeExamineState"
                          style="height: 26px; line-height: 26px"
                          >{{ $t('待审核') }}</span
                        >
                      </template>
                    </div>
                  </el-form-item>
                  <el-form-item
                    :label="$t('会员类型：')"
                    v-else-if="routeQuery.contractSource == 2"
                  >
                    <!-- <el-input disabled v-model="templateDetail.classificationName"></el-input> -->
                    {{ templateDetail.classificationName }}
                  </el-form-item>
                  <el-form-item :label="$t('评审单号：')" v-else>
                    <!-- <el-input disabled v-model="templateDetail.judgeNumber" style="width: 80%"></el-input> -->
                    {{ templateDetail.judgeNumber }}
                    <span style="font-size: 12px; margin-left: 10px">{{
                      templateDetail.formStateStr
                    }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="24" v-if="routeQuery.contractSource != 1">
                  <el-form-item :label="$t('合同编号：')">
                    <!-- <el-input disabled v-model="templateDetail.contractNumber"></el-input> -->
                    {{ templateDetail.contractNumber }}
                  </el-form-item>
                </el-col>
                <el-col :span="24" v-if="routeQuery.formQuery">
                  <el-form-item :label="$t('版本号：')">
                    <!-- <el-input disabled v-model="templateDetail.contractVersion"></el-input> -->
                    {{ templateDetail.contractVersion }}
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item :label="$t('模板类型：')">
                    <!-- <el-input disabled v-model="templateDetail.definition"></el-input> -->
                    {{ templateDetail.definition }}
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item :label="$t('模板：')">
                    <!-- <el-input disabled v-model="templateDetail.templateType"></el-input> -->
                    {{ templateDetail.templateType }}
                  </el-form-item>
                </el-col>
                <el-col :span="24" v-if="routeQuery.contractSource != 2">
                  <el-form-item :label="$t('合同创建人：')">
                    <!-- <el-input disabled v-model="templateDetail.createdUserName"></el-input> -->
                    {{ templateDetail.createdUserName }}
                  </el-form-item>
                </el-col>
                <el-col :span="24" v-if="routeQuery.contractSource == 1">
                  <el-form-item
                    :label="$t('新版本生效时间：')"
                    prop="newVersionEffectiveDate"
                  >
                    <el-date-picker
                      :disabled="!!routeQuery.readonly"
                      v-model="templateDetail.newVersionEffectiveDate"
                      type="date"
                      :placeholder="$t('选择日期')"
                      value-format="yyyy-MM-dd"
                      clearable
                      :picker-options="pickOptions"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="24" v-if="routeQuery.contractSource == 3">
                  <el-form-item :label="$t('关联的合同编号：')">
                    <!-- <el-input disabled v-model="templateDetail.parentContractNumber"></el-input> -->
                    {{ templateDetail.parentContractNumber }}
                  </el-form-item>
                </el-col>
              </div>
              <el-col
                :span="24"
                v-if="
                  firstContractCategory.firstContractCategoryDtoList &&
                  firstContractCategory.firstContractCategoryDtoList.length
                "
              >
                <el-form-item
                  :label="$t('合同一级分类：')"
                  prop="firstContractCategoryCode"
                >
                  <el-select
                    v-model="templateDetail.firstContractCategoryCode"
                    :disabled="!!routeQuery.readonly"
                    @change="changeCategory(1)"
                  >
                    <el-option
                      v-for="item in firstContractCategory.firstContractCategoryDtoList"
                      :key="item.categoryCode"
                      :value="item.categoryCode"
                      :label="item.categoryName"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col
                :span="24"
                v-if="
                  secondContractCategory.secondContractCategoryDtoList &&
                  secondContractCategory.secondContractCategoryDtoList.length
                "
              >
                <el-form-item
                  :label="$t('合同二级分类：')"
                  prop="secondContractCategoryCode"
                >
                  <el-select
                    v-model="templateDetail.secondContractCategoryCode"
                    :disabled="!!routeQuery.readonly"
                    @change="changeCategory(2)"
                  >
                    <el-option
                      v-for="item in secondContractCategory.secondContractCategoryDtoList"
                      :key="item.categoryCode"
                      :value="item.categoryCode"
                      :label="item.categoryName"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <template v-if="routeQuery.formQuery">
              <el-row>
                <el-col :span="24">
                  <el-form-item :label="$t('期限状态：')">
                    <span
                      v-if="templateDetail.termStatus == 1"
                      class="statusAwait"
                      >{{ $t('未开始') }}</span
                    >
                    <span
                      v-if="templateDetail.termStatus == 2"
                      class="statusSucccess"
                      >{{ $t('进行中') }}</span
                    >
                    <span
                      v-if="templateDetail.termStatus == 3"
                      class="statusFailed"
                      >{{ $t('已超期') }}</span
                    >
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item :label="$t('冻结状态：')">
                    <span
                      v-if="templateDetail.freezeState == 0"
                      class="statusSucccess"
                      >{{ $t('未冻结') }}</span
                    >
                    <span
                      v-if="templateDetail.freezeState == 1"
                      class="statusFailed"
                      >{{ $t('已冻结') }}</span
                    >
                    <span v-if="templateDetail.freezeRemark"
                      >({{ templateDetail.freezeRemark }})</span
                    >
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item :label="$t('签章状态：')">
                    <span
                      v-if="templateDetail.signatureState == 1"
                      class="statusAwait"
                      >{{ $t('待签章') }}</span
                    >
                    <span
                      v-if="templateDetail.signatureState == 2"
                      class="statusSucccess"
                      >{{ $t('已签章') }}</span
                    >
                    <span
                      v-if="templateDetail.signatureState == 3"
                      class="statusSucccess"
                      >{{ $t('无需签章') }}</span
                    >
                    <span
                      v-if="templateDetail.signatureState == 4"
                      class="statusFailed"
                      >{{ $t('不可签章') }}</span
                    >
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item :label="$t('签章附件：')">
                    <div class="file-list">
                      <div
                        class="file-item"
                        v-for="(item, index) in templateDetail.filesDtoList"
                        :key="index"
                      >
                        <span @click="downloadFile(item)">{{
                          item.fileName
                        }}</span>
                      </div>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
            <template v-if="routeQuery.changeId && routeQuery.readonly">
              <el-form-item :label="$t('变更详情：')">
                <change-detail :detail="templateDetail"></change-detail>
              </el-form-item>
            </template>
            <template
              v-if="
                routeQuery.formState == 2 ||
                routeQuery.contractChangeExamineState == 2
              "
            >
              <el-form-item :label="$t('驳回原因：')">
                <el-input
                  disabled
                  v-model="templateDetail.examineOpinion"
                ></el-input>
              </el-form-item>
            </template>
          </el-form>
        </div>

        <div
          class="add-contract-part-con"
          v-for="item in templateDetail.parameterClassifyList"
          :key="item.parameterClassifyNumber"
        >
          <div class="add-contract-part-con-title">
            {{ item.parameterClassifyName }}
          </div>
          <div class="add-contract-part-con-form">
            <contractForm
              :ref="item.parameterClassifyNumber"
              :list="item.headerList"
              :detail="templateDetail"
              :cols="3"
              :definitionId="templateDetail.definitionId"
              @changeRule="changeRule"
            ></contractForm>
          </div>
        </div>
        <van-collapse v-model="activeNames">
          <div
            class="add-contract-part-con"
            v-for="(item, idx) in templateDetail.projectDetailClassification"
            :key="item.projectDetailCode"
          >
            <van-collapse-item :name="idx">
              <template #title>
                <div class="add-contract-part-con-title">
                  {{ item.projectDetailTitle }}
                </div>
              </template>
              <div class="add-contract-part-con-form">
                <!-- <el-button type="primary" v-if="!readonly && item.projectList && item.projectList.length < 50" @click="handleData(1, idx, item)">{{ $t('添加') }}</el-button>
                {{ customColumns }}
                  <el-button type="text" v-if="!readonly" @click="handleData(2, idx, item, row, index)">{{ $t('修改') }}</el-button>
                <el-button type="text" v-if="readonly" @click="handleData(3, idx, item, row, index)">{{ $t('详情') }}</el-button>
                <el-button type="text" v-if="!readonly" @click="handleDel(index, idx)">{{ $t('删除') }}</el-button> -->
                <customColumnTable
                  ref="table"
                  v-if="visible"
                  :type="6"
                  :definitionCode="$route.query.definitionCode"
                  :templateTypeCode="templateDetail.templateTypeCode"
                  :projectDetailCode="item.projectDetailCode"
                  :customColumns="customColumns"
                  :widthObj="widthObj"
                  :fixedObj="fixedObj"
                  :pageNumber="0"
                  :local-data="item.projectList"
                  :showOpt="true"
                >
                  <template slot="button">
                    <el-button
                      type="primary"
                      v-if="
                        !readonly &&
                        item.projectList &&
                        item.projectList.length < 50
                      "
                      @click="handleData(1, idx, item)"
                      >{{ $t('添加') }}</el-button
                    >
                  </template>
                  <template slot-scope="{ row, column }">
                    <!-- 货品、品名、型号、来源订单大类、库区类型、作业时间 -->
                    <template
                      v-if="
                        [
                          'Goods',
                          'category',
                          'modelConfigs',
                          'orderTypes',
                          'stockRegionTypes',
                          'workTime',
                        ].includes(column.columnName)
                      "
                    >
                      <template
                        v-if="
                          row.parameterDtoList && row.parameterDtoList.length
                        "
                      >
                        <template
                          v-if="
                            row.parameterDtoList.some(
                              (it) => it.parameterNumber === column.columnName
                            )
                          "
                        >
                          <template
                            v-for="(it, idx) in row.parameterDtoList.filter(
                              (it) => it.parameterNumber === column.columnName
                            )"
                          >
                            <template v-if="it.projectValue">
                              {{
                                statusObj[JSON.parse(it.projectValue).limitType]
                              }}
                              {{
                                JSON.parse(it.projectValue).limitType == 2
                                  ? JSON.parse(it.projectValue).value
                                  : ''
                              }}
                            </template>
                          </template>
                        </template>
                      </template>
                    </template>
                    <!-- 固定属性 -->
                    <template v-if="column.columnName == 'fixedTypes'">
                      <template
                        v-if="
                          row.parameterDtoList && row.parameterDtoList.length
                        "
                      >
                        <template
                          v-if="
                            row.parameterDtoList.some(
                              (it) => it.parameterNumber === column.columnName
                            )
                          "
                        >
                          <template
                            v-for="(it, idx) in row.parameterDtoList.filter(
                              (it) => it.parameterNumber === column.columnName
                            )"
                          >
                            <template
                              v-if="
                                it.projectValue &&
                                JSON.parse(it.projectValue) &&
                                JSON.parse(it.projectValue).limitType == 2 &&
                                JSON.parse(it.projectValue).propertyInfos &&
                                JSON.parse(it.projectValue).propertyInfos.length
                              "
                            >
                              <p
                                v-for="(item, index) in JSON.parse(
                                  it.projectValue
                                ).propertyInfos"
                                :key="index"
                              >
                                {{
                                  item.propertyName
                                    ? item.propertyName +
                                      ':' +
                                      item.propertyValue
                                    : ''
                                }}
                              </p>
                            </template>
                          </template>
                        </template>
                      </template>
                    </template>
                  </template>
                  <template slot="tableOpt" slot-scope="{ row, index }">
                    <el-button
                      type="text"
                      v-if="!readonly"
                      @click="handleData(2, idx, item, row, index)"
                      >{{ $t('修改') }}</el-button
                    >
                    <el-button
                      type="text"
                      v-if="readonly"
                      @click="handleData(3, idx, item, row, index)"
                      >{{ $t('详情') }}</el-button
                    >
                    <el-button
                      type="text"
                      v-if="!readonly"
                      @click="handleDel(index, idx)"
                      >{{ $t('删除') }}</el-button
                    >
                  </template>
                </customColumnTable>
              </div>
            </van-collapse-item>
          </div>
        </van-collapse>
        <projectDetail
          v-if="dialogVisible"
          :detail="templateDetail"
          :tableData="
            templateDetail.projectDetailClassification[projectIndex].projectList
          "
          :dialogVisible="dialogVisible"
          :rowList="rowList"
          :type="type"
          :index="index"
          :id="templateDetail.definitionId"
          :projectDetailCode="projectDetailItem.projectDetailCode"
          :headerValueList="getHeaderInfo()"
          @closeProjectDetail="dialogVisible = false"
          @addData="addData"
          @editData="editData"
        />
      </div>
      <div v-if="activeName === 'second'">
        <history :contractId="templateDetail.definitionId" />
      </div>
    </div>
    <div class="add-contract-button" v-if="$route.query.readonly">
      <!-- <detailFootButton :oaFlag="templateDetail.oaFlag"></detailFootButton> -->
      <el-button type="default" @click="handleBack">{{ $t('取消') }}</el-button>
    </div>
    <div class="add-contract-button" v-else>
      <el-button type="primary" @click="confirm">{{ $t('确定') }}</el-button>
    </div>
  </div>
</template>
<script>
import contractCreationService from '@/services/contractCreationService'
import contractForm from '@/views/personalCenter/components/contractForm.vue'
import projectDetail from '@/views/personalCenter/components/projectDeatil.vue'
import nonStandardService from '@/services/nonStandardService'
import eventBus from '@/assets/utils/eventBus.js'
// import detailFootButton from './detailFootButton'
import customColumnTable from '@/components/customColumnTable.vue'
import history from './components/history.vue'
import { Toast } from 'vant'

export default {
  components: { contractForm, projectDetail, customColumnTable, history },
  data() {
    return {
      activeNames: [],
      activeName: 'first',
      routeQuery: {},
      templateDetail: {},
      dialogVisible: false,
      type: null,
      index: null,
      rowList: {},
      readonly: false,
      searchData: {},
      tableData: [],
      processCode: '',
      formState: '',
      page: {
        nowPage: 1,
        pageSize: 10,
        total: 0,
      },
      flowData: [],
      flowCols: [
        {
          columnTitle: this.$t('流程节点名称'),
          columnName: 'nodeName',
          // isCopy: true,
        },
        {
          columnTitle: this.$t('审批人姓名'),
          columnName: 'createdByName',
        },
        {
          columnTitle: this.$t('审批人部门'),
          columnName: 'deptName',
        },
        {
          columnTitle: this.$t('审批状态'),
          columnName: 'actionName',
        },
        {
          columnTitle: this.$t('审批开始时间'),
          columnName: 'createdTime',
        },
        {
          columnTitle: this.$t('处理时间'),
          columnName: 'endTime',
        },
        {
          columnTitle: this.$t('操作描述'),
          columnName: 'actionDesc',
        },
        {
          columnTitle: this.$t('审批意见'),
          columnName: 'messageText',
        },
      ],

      enterPageTime: null,
      statusObj: {
        1: this.$t('【不限】'),
        2: this.$t('【指定】'),
      },
      stateMap: new Map([
        [0, this.$t('待审核')],
        [1, this.$t('已通过')],
        [2, this.$t('未通过')],
        [3, this.$t('审核中')],
      ]),
      visible: true,
      customColumns: {
        Goods: true,
        category: true,
        fixedTypes: true,
        modelConfigs: true,
        orderTypes: true,
        stockRegionTypes: true,
        workTime: true,
      },
      widthObj: {},
      fixedObj: {
        projectNumber: 'left',
      },
      serviceTypeOpts: [],
      settlementModeOpts: [],
      leaseTypeOpts: [
        { value: 1, label: this.$t('租赁资源') },
        // { value: 2, label: '附属设施' },
      ],
      projectIndex: null,
      projectDetailItem: {},
      firstContractCategory: {},
      secondContractCategory: {},
      rules: {
        newVersionEffectiveDate: [
          {
            required: true,
            message: this.$t('请选择新版本生效时间'),
            trigger: 'change',
          },
        ],

        firstContractCategoryCode: [
          {
            required: true,
            message: this.$t('请选择一级合同类别'),
            trigger: 'change',
          },
        ],

        secondContractCategoryCode: [
          {
            required: true,
            message: this.$t('请选择二级合同类别'),
            trigger: 'change',
          },
        ],
      },
      pickOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now()
        },
      },
      loading: false,
    }
  },
  created() {
    this.routeQuery = this.$route.query
    this.readonly = Boolean(this.$route.query.readonly)
    this.queryDetailForAdd()
    this.getDate()
  },
  methods: {
    handleClick(v) {
      if (v.name == 'second') {
        this.getFlowList()
      }
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.page.pageNum = 1
      this.getFlowList()
    },
    handleCurrentChange(val) {
      this.page.pageNum = val
      this.getFlowList()
    },
    async getFlowList() {
      // 获取OA审批流程列表
      const params = {
        formId: this.routeQuery.formId,
      }
      try {
        const data = await contractCreationService.queryContractApprovalList(
          params
        )
        if (data.code == 200) {
          this.flowData = data.data.processSortList
          this.processCode = data.data.processCode
          this.formState = data.data.formState
          this.oaProcessId = data.data.oaProcessId
        }
      } catch (error) {
        console.log(error)
      }
    },
    async handleWith() {
      this.$confirm(
        this.$t('当前合同审批中，请确认是否操作撤回？'),
        this.$t('提示'),
        {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning',
        }
      )
        .then(async () => {
          // 撤回审批
          try {
            const data = await contractCreationService.cancelContractApproval({
              // contractFormId: this.routeQuery.formId,
              oaProcessId: this.oaProcessId,
              userCode: localStorage.getItem('userMCode'),
            })
            if (data.code == 200) {
              this.$message.success(this.$t('操作成功'))
              this.handleBack()
            }
          } catch (error) {
            console.log(error)
          }
        })
        .catch(() => {})
    },
    getServiceType() {
      nonStandardService
        .queryServiceTypeInfo({ ecologyCode: 'WMS', eventState: 1 })
        .then((res) => {
          if (res.code == 200) {
            this.serviceTypeOpts =
              res.data.amsPriceEventInfos &&
              res.data.amsPriceEventInfos.map((it) => {
                return {
                  ...it,
                  label: it.eventCode + it.eventName,
                  value: it.eventCode,
                }
              })
          }
        })
    },
    getSettlementMode() {
      let params = {
        code: 'settlementMode',
      }
      let templateTypeCode = this.templateDetail.templateTypeCode
      params.templateTypeCode = templateTypeCode
      switch (templateTypeCode) {
        case 'TMSHZ': //多式联运货主
          params.ecology = 'TMS'
          params.memberType = 1
          break
        case 'TMSCYS': //多式联运承运商
          params.ecology = 'TMS'
          params.memberType = 3
          break
        case 'TMSSJ': //多式联运个体司机
          params.ecology = 'TMS'
          params.memberType = 4
          break
        case 'TMSCLB': //多式联运车老板
          params.ecology = 'TMS'
          params.memberType = 5
          break
        case 'WMSHZ1': //仓储货主（通用）
          params.ecology = 'WMS'
          params.memberType = 6
          params.industry = 1
          break
        case 'WMSHZ2': //仓储货主（行业）
          params.ecology = 'WMS'
          params.memberType = 6
          params.industry = 2
          break
      }
      // 接口
      nonStandardService.basicConfiguration(params).then((res) => {
        if (res.code == 200) {
          this.settlementModeOpts = res.data
        }
      })
    },
    getDate() {
      let now = new Date()
      const year = now.getFullYear()
      const month = now.getMonth() + 1
      const day = now.getDate()
      const h = now.getHours() < 10 ? '0' + now.getHours() : now.getHours()
      const m =
        now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes()
      const s =
        now.getSeconds() < 10 ? '0' + now.getSeconds() : now.getSeconds()
      let data = year + '-' + month + '-' + day
      let times = h + ':' + m + ':' + s
      this.enterPageTime = data + ' ' + times
    },
    queryDetailForAdd() {
      this.loading = true
      let api = null
      if (this.routeQuery.contractSource == 3) {
        api = contractCreationService.queryContractFormRenewArgs({
          formId: this.routeQuery.formId,
          templateDefinitionCode: this.routeQuery.definitionCode,
          pageType: this.routeQuery.readonly ? 3 : 1,
        })
      } else {
        api = contractCreationService.detailForAdd({
          formId: this.routeQuery.formId, //再来一单的合同id
          definitionId: this.routeQuery.definitionId,
          definitionCode: this.routeQuery.definitionCode,
          contractSource: this.routeQuery.isFromChange
            ? 0
            : this.routeQuery.contractSource || 0, //自动创建的时候传1
          latestTemplateFlag: !this.routeQuery.readonly ? 1 : undefined, //除了详情  其余的应该都是最新的
        })
      }
      api
        .then((res) => {
          this.loading = false
          let createdUserName =
            localStorage.getItem('userName') +
            localStorage.getItem('userRealName')
          //重新提交取当前登录人的信息
          if (
            res.data.createdUserName &&
            !this.$route.query.reSubmit &&
            !this.$route.query.copy
          ) {
            createdUserName = res.data.createdUserName
          }
          // 由于日期格式存储是{value: 'xxx'},除wms外的日期都是标准字段，需特殊处理一下，取出value值
          let wmsFlag = ['WMSHZ1', 'WMSHZ2'].includes(res.data.templateTypeCode)
          this.templateDetail = {
            ...res.data,
            definition: res.data.definitionCode + res.data.definitionName,
            templateType: res.data.templateTypeCode + res.data.templateTypeName,
            parentFormId: this.routeQuery.formId,
            parameterClassifyList: (res.data.parameterClassifyList || []).map(
              (it) => {
                ;(it.headerList || []).map((item) => {
                  let parameterValue = item.parameterValueStr
                    ? JSON.parse(item.parameterValueStr)
                    : {}
                  let dateFalg =
                    item.parameterType == 5 && parameterValue.timeCount == 2
                  if (item.parameterType == 4) {
                    item.defaultValue =
                      item.defaultValue && JSON.parse(item.defaultValue)
                  }
                  item.defaultValue =
                    dateFalg && !wmsFlag
                      ? item.defaultValue && JSON.parse(item.defaultValue).value
                      : item.defaultValue
                })
                return {
                  ...it,
                }
              }
            ),
            projectDetailClassification: (
              res.data.projectDetailClassification || []
            ).map((its) => {
              const projectList = (its.projectList || []).map((it) => {
                ;(it.projectDefaultDtoList || []).map((item) => {
                  if (item.parameterType == 4) {
                    item.defaultValue =
                      item.defaultValue && JSON.parse(item.defaultValue)
                  }
                  it[item.parameterNumber] =
                    item.defaultValue && item.defaultValue.indexOf('{') === 0
                      ? JSON.parse(item.defaultValue).value
                      : item.defaultValue
                  it.value = item.defaultValue
                  it.projectValue = item.defaultValue
                  it.projectNumber = it.projectNumber
                })
                return {
                  ...it,
                  parameterDtoList: (it.projectDefaultDtoList || []).map(
                    (its) => {
                      return {
                        ...its,
                        projectValue: its.defaultValue,
                        value: its.defaultValue,
                        projectNumber: its.projectNumber,
                      }
                    }
                  ),
                  parameterProductList: (it.projectDefaultDtoList || []).map(
                    (its) => {
                      return {
                        ...its,
                        projectValue: its.defaultValue,
                        value: its.defaultValue,
                        projectNumber: its.projectNumber,
                      }
                    }
                  ),
                }
              })
              return {
                ...its,
                projectList: projectList,
              }
            }),
            createdUserName: createdUserName,
          }
          this.$store.dispatch(
            'contract/setHeaderData',
            this.templateDetail.parameterClassifyList
          )
          this.$store.dispatch(
            'contract/setProjectData',
            this.templateDetail.projectDetailClassification
          )
          this.$store.dispatch('contract/setHeaderForm', {})
          this.$tableData = JSON.parse(
            JSON.stringify(this.templateDetail.projectDetailClassification)
          )
          this.templateDetail.judgeNumber = this.$route.query.judgeNumber
          this.templateDetail.changeNumber = this.$route.query.changeNumber
          this.firstContractCategory = res.data.firstContractCategory
          this.secondContractCategory = res.data.secondContractCategory
          if (!!this.$route.query.copy) {
            this.templateDetail.judgeNumber = ''
            this.templateDetail.contractNumber = ''
          }
          if (this.readonly) {
            this.getServiceType()
            this.getSettlementMode()
          }
        })
        .catch(() => (this.loading = false))
    },
    queryDetail(idx) {
      let tableData = JSON.parse(
        JSON.stringify(this.$tableData[idx].projectList)
      )
      let arr = tableData.map((it) => {
        return {
          ...it,
        }
      })
      Object.keys(this.searchData).forEach((e) => {
        // 调用自己定义好的筛选方法
        arr = this.filterFunc(this.searchData[e], e, arr)
      })
      // 为表格赋值
      this.templateDetail.projectDetailClassification[idx].projectList = arr
    },
    /*
        val: 查询条件的值
        target: 目标参数，就是你这个值对应的key
        filterarr: 被筛选的数组
    */
    filterFunc(val, target, filterArr) {
      // 参数不存在或为空时，就相当于查询全部
      if (val == undefined || val == '') return filterArr
      // 根据条件筛选
      if (target == 'projectNumber') {
        return filterArr.filter((p) => String(p[target]) == val)
      } else {
        return filterArr.filter((p) => String(p[target]).includes(val))
      }
    },
    /**
     * type: 操作类型 1新增 2修改 3详情
     * idx: 项目明细索引
     * item: 项目明细
     * row: 明细行信息
     * index: 明细行索引
     */
    handleData(type, idx, item, row, index) {
      this.projectIndex = idx
      this.projectDetailItem = item
      // type 1新增 2修改
      this.index = index
      this.type = type
      if (type != 1) {
        this.rowList = {
          ...row,
          parameterProductList: (row.parameterDtoList || []).map((it) => {
            let defaultValue =
              it.defaultValue || it.value || it.projectValue || ''
            if (typeof defaultValue == 'string') {
              // 处理复选
              if (defaultValue.startsWith('[')) {
                defaultValue = JSON.parse(defaultValue)
              }
              // 处理日期组格式
              if (defaultValue.startsWith('{') && it.parameterType == 5) {
                defaultValue = JSON.parse(defaultValue).value
              }
            }
            return {
              ...it,
              defaultValue,
            }
          }),
        }
        this.dialogVisible = true
      } else {
        this.dialogVisible = true
      }
    },
    handleDel(index) {
      this.templateDetail.projectDetailClassification[
        this.projectIndex
      ].projectList.splice(index, 1)
      this.changeProject()
    },
    getList(data) {
      let list = [{}]
      list.forEach((it) => {
        data.projectParameterList &&
          data.projectParameterList.forEach((item) => {
            it[item.parameterNumber] =
              item.projectValue && item.projectValue.indexOf('{') === 0
                ? JSON.parse(item.projectValue).value
                : item.projectValue
            it.projectNumber = data.projectNumber
            return {
              ...it,
            }
          })
      })
      let obj = {
        ...data,
        ...list[0],
        parameterProductList:
          data.projectParameterList &&
          data.projectParameterList.map((it) => {
            return {
              ...it,
              parameterValue: it.projectValue,
            }
          }),
        parameterDtoList:
          data.projectParameterList &&
          data.projectParameterList.map((it) => {
            return {
              ...it,
              parameterValue: it.projectValue,
            }
          }),
      }
      return obj
    },
    addData(data) {
      let obj = this.getList(data)
      console.log(obj, 'obj')
      this.templateDetail.projectDetailClassification[
        this.projectIndex
      ].projectList.push(obj)
      this.changeProject()
    },
    editData(data) {
      const projectList = this.templateDetail.projectDetailClassification[
        this.projectIndex
      ].projectList.map((item, index) => {
        if (index == this.index) {
          let obj = this.getList(data)
          item = JSON.parse(JSON.stringify(obj))
        }
        return item
      })
      this.$set(
        this.templateDetail.projectDetailClassification[this.projectIndex],
        'projectList',
        projectList
      )
      this.changeProject()
    },
    changeProject() {
      eventBus.$emit(
        'changeProject',
        this.templateDetail.projectDetailClassification[this.projectIndex]
          .projectList
      )
    },
    changeCategory(type) {
      let obj = {}
      if (type == 1) {
        obj = this.firstContractCategory
      }
      if (type == 2) {
        obj = this.secondContractCategory
      }
      if (obj.relatedRuleFieldList && obj.relatedRuleFieldList.length) {
        this.changeRule(obj)
      }
    },
    changeRule(row) {
      let arr = this.getHeaderInfo()
      const firstContractCategoryCode =
        this.templateDetail.firstContractCategoryCode
      const secondContractCategoryCode =
        this.templateDetail.secondContractCategoryCode
      if (firstContractCategoryCode) {
        arr.push({
          ruleFieldKey: this.firstContractCategory.ruleFieldKey,
          headerValue: firstContractCategoryCode,
        })
      }
      if (secondContractCategoryCode) {
        arr.push({
          ruleFieldKey: this.secondContractCategory.ruleFieldKey,
          headerValue: secondContractCategoryCode,
        })
      }
      const params = {
        definitionId: this.templateDetail.definitionId,
        relatedRuleFieldList: row.relatedRuleFieldList,
        filledRuleFieldList: (arr || []).map((it) => {
          return {
            ruleFieldKey: it.ruleFieldKey,
            ruleValue: it.headerValue,
          }
        }),
      }
      const list = this.templateDetail.parameterClassifyList
      this.loading = true
      contractCreationService
        .calcTemplateDefinitionRuleField(params)
        .then((res) => {
          this.loading = false
          // 抬头信息规则处理
          const headerArr = res.data.headerRuleFieldCalculateDtoList
          // 塞默认值
          let headerList = (list || []).map((its) => {
            ;(its.headerList || []).map((it) => {
              ;(arr || []).map((item) => {
                if (it.parameterNumber === item.parameterNumber) {
                  let headerValue = item.headerValue
                  const parameterValue =
                    JSON.parse(item.parameterValueStr) || {}
                  if (
                    (parameterValue.timeCount == 2 ||
                      item.parameterType == 4) &&
                    headerValue
                  ) {
                    if (JSON.parse(headerValue).value) {
                      headerValue = JSON.parse(headerValue).value
                    } else {
                      headerValue = JSON.parse(headerValue)
                    }
                  }
                  it.defaultValue = headerValue
                }
              })
            })
            return its
          })
          // 根据规则塞值
          this.templateDetail.parameterClassifyList = (headerList || []).map(
            (its) => {
              ;(its.headerList || []).map((it) => {
                ;(headerArr || []).map((item) => {
                  if (it.parameterNumber === item.parameterNumber) {
                    let defaultValue = item.defaultValue
                    const parameterValue =
                      JSON.parse(item.parameterValueStr) || {}
                    // 处理数组格式
                    if (
                      (parameterValue.timeCount == 2 ||
                        item.parameterType == 4) &&
                      defaultValue
                    ) {
                      if (JSON.parse(defaultValue).value) {
                        defaultValue = JSON.parse(defaultValue).value
                      } else {
                        defaultValue = JSON.parse(defaultValue)
                      }
                    }
                    it.defaultValue = defaultValue
                      ? defaultValue
                      : it.defaultValue
                    it.state = item.state
                  }
                })
                return it
              })
              return its
            }
          )

          // 项目明细规则处理，如果抬头信息里的规则触发了项目明细，则项目明细清空
          const projectArr = res.data.projectRuleFieldCalculateDtoList
          if (projectArr && projectArr.length) {
            const projectData = this.templateDetail.projectDetailClassification
            this.templateDetail.projectDetailClassification = (
              projectData || []
            ).map((it) => {
              ;(projectArr || []).map((its) => {
                if (its.groupCode === it.projectDetailCode) {
                  it.projectList = []
                }
              })
              return it
            })
          }
        })
        .catch(() => (this.loading = false))
    },
    // 页面填写的抬头信息默认值
    getHeaderInfo() {
      let arr = this.$store.state.contract.headerData
      const obj = this.$store.state.contract.headerForm
      arr = arr.map((it) => {
        return {
          ...it,
          headerValue:
            typeof obj[it.parameterNumber] === 'string'
              ? obj[it.parameterNumber]
              : JSON.stringify(obj[it.parameterNumber]),
        }
      })
      return arr
    },
    confirm() {
      const formValid = this.$refs.templateForm.validate()
      let def = []
      if (formValid) {
        def.push(formValid)
      }
      let vm = this
      this.templateDetail.parameterClassifyList.forEach((it) => {
        def.push(vm.$refs[it.parameterClassifyNumber][0].getData())
      })
      Promise.all(def).then((res) => {
        let arr = []
        res.forEach((it) => {
          arr = it && it.length ? arr.concat(it) : arr
        })
        let params = {
          definitionId: this.routeQuery.definitionId,
          definitionCode: this.routeQuery.definitionCode,
          contractSource: this.routeQuery.contractSource || 0,
          parameterList: arr,
          projectDetailClassification: (
            this.templateDetail.projectDetailClassification || []
          ).map((its) => {
            const projectDetailList = (its.projectList || []).map((it) => {
              return {
                projectNumber: it.projectNumber,
                projectParameterList: (it.parameterProductList || []).map(
                  (item) => {
                    const projectValue = item.defaultValue || item.projectValue
                    return {
                      parameterNumber: item.parameterNumber,
                      projectValue:
                        typeof projectValue === 'string'
                          ? projectValue
                          : JSON.stringify(projectValue),
                      parameterType: item.parameterType,
                    }
                  }
                ),
                parameterProductList: undefined,
              }
            })
            return {
              projectDetailCode: its.projectDetailCode,
              projectDetailTitle: its.projectDetailTitle,
              projectDetailList,
            }
          }),
          enterPageTime: this.enterPageTime, //进入当前页面的时间，后端拿来和模板修改的时间做对比
          firstContractCategoryCode:
            this.templateDetail.firstContractCategoryCode,
          secondContractCategoryCode:
            this.templateDetail.secondContractCategoryCode,
        }
        let api = null
        if (this.routeQuery.pageType == 2) {
          // 合同自动创建修改
          api = contractCreationService.editContractForm({
            ...params,
            formId: this.routeQuery.formId,
          })
        } else {
          // contractSource 1-自动 2-变更 3-续签
          if (this.routeQuery.contractSource == 1) {
            api = contractCreationService.contractChange({
              ...params,
              oldFormId: this.routeQuery.formId,
              newVersionEffectiveDate:
                this.templateDetail.newVersionEffectiveDate,
            })
          } else if (this.routeQuery.contractSource == 2) {
            api = contractCreationService.autoAddContractForm(params)
          } else if (this.routeQuery.contractSource == 3) {
            api = contractCreationService.renewContractForm({
              ...params,
              parentFormId: this.templateDetail.parentFormId,
              parentContractNumber: this.templateDetail.parentContractNumber,
            })
          } else {
            // 判断仓储是否多选
            let flag = false
            if (this.templateDetail.templateTypeCode == 'WMSHZ1') {
              ;(params.parameterList || []).map((it) => {
                if (it.parameterNumber == 'warehouse') {
                  let list = JSON.parse(it.headerValue)
                  if (list && list.length > 1) {
                    flag = true
                  } else {
                    if (list && list.length === 1) {
                      it.headerValue = JSON.stringify(list[0])
                    }
                  }
                }
              })
            }
            if (flag) {
              contractCreationService
                .batchAddContractForm(params)
                .then((res) => {
                  this.$confirm(res.data.resultMsg, this.$t('提示'), {
                    confirmButtonText: this.$t('我知道了'),
                    showClose: false,
                    closeOnClickModal: false,
                    showCancelButton: false,
                  }).then(() => {
                    this.handleBack()
                  })
                })
                .catch((res) => {
                  this.$confirm(res.data.resultMsg, this.$t('提示'), {
                    confirmButtonText: this.$t('我知道了'),
                    showClose: false,
                    closeOnClickModal: false,
                    showCancelButton: false,
                  }).then(() => {
                    this.handleBack()
                  })
                })
            } else {
              api = contractCreationService.addContractForm(params)
            }
          }
        }
        if (api) {
          api.then((res) => {
            // this.$message.success('')
            Toast.success(this.$t('操作成功'))
            this.handleBack()
          })
        }
      })
    },
    handleBack() {
      // this.goRouteBack(this.$route.name)
      // this.$router.push({
      //   path: '/contract/createList'
      // })
      this.$router.go(-1)
      localStorage.removeItem('warehouseId')
      localStorage.removeItem('warehouse')
      localStorage.removeItem('parkCode')
      localStorage.removeItem('startEndTime')
    },
    downloadFile(item) {
      window.open(item.fileUrl)
    },
  },
}
</script>
<style lang="scss">
.base-box {
  background: #f6f7fd;
  border-radius: 4px;
  min-height: 180px;
  margin-bottom: 10px;
}
.flow-art {
  display: flex;
  align-items: center;
  &-title {
    margin-right: 20px;
  }
}
.add-contract {
  .add-contract-part {
    background: #f5f8fc;
    border-radius: 8px;
    margin-bottom: 17px;
    padding: 0px 1px;
  }
  .add-contract-title {
    border-bottom: 1px solid #eeeeee;
    padding: 20px 15px;
  }
  .add-contract-base {
    padding: 6px;
    background: #fff;
    margin: 6px;
  }
  .add-contract-part-con {
    margin: 6px;
    background: #fff;
    // border: 1px solid #eeeff2;
    padding: 6px;
  }
  .add-contract-part-con-title {
    position: relative;
    padding-left: 10px;
    font-size: 16px;
    height: 23px;
    color: #333333;
    line-height: 23px;
    margin-bottom: 10px;
    &::before {
      position: absolute;
      top: 3px;
      left: 0;
      content: '';
      display: block;
      clear: both;
      width: 1px;
      height: 15px;
      border-left: 2px solid #364dd7;
    }
  }
  .add-contract-button {
    background: #ffffff;
    box-shadow: 0px -2px 4px 0px rgba(0, 0, 0, 0.07);
    text-align: center;
    padding: 10px 0px;
    box-sizing: border-box;
    // position: fixed;
    // left: 0;
    // right: 0;
    // bottom: 0;
  }
  .info {
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .info-item {
    overflow-x: hidden;
    text-overflow: ellipsis;
    height: 112px;
  }
  .info-item2 {
    overflow-y: scroll;
  }
  .file-item {
    cursor: pointer;
  }
}
</style>
